package com.jic.market.controller.manage;

import com.jic.common.base.vo.PageResult;
import com.jic.common.base.vo.RestResult;
import com.jic.market.api.manage.PromotionProductManageApi;

import com.jic.market.common.enums.*;
import com.jic.market.common.util.ListUtils;
import com.jic.market.entity.PromotionLimitRuleEntity;
import com.jic.market.entity.PromotionMerchantProductEntity;
import com.jic.market.orm.Pagination;
import com.jic.market.request.*;
import com.jic.market.response.*;
import com.jic.market.service.PromotionLimitRuleService;
import com.jic.market.service.PromotionMerchantProductService;
import com.jic.market.service.PromotionMutexService;
import com.jic.market.service.PromotionSingleLimitRuleService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author xuyongliang
 * @version V1.0
 * @className PromotionProductManageController
 * @description TODO
 * @date 2020/1/16 2:56 PM
 */

@RestController
@RequestMapping("/product")
@Slf4j
public class PromotionProductManageController implements PromotionProductManageApi{

    @Resource
    private PromotionMerchantProductService pmpService;

    @Resource
    PromotionLimitRuleService limitService;


    @Resource
    private PromotionMutexService promotionMutexService;

    @Resource
    private PromotionSingleLimitRuleService promotionSingleLimitRuleService;


    @PostMapping("/saveBatch")
    @Override
    public RestResult<Integer> saveBatch(@RequestBody PromotionProductSaveListRequest ppr) {

        List<Long> productIds =new ArrayList<>();
        List<PromotionProductRequest> pprList =ppr.getProductPromotionList();
        for (PromotionProductRequest promotionProductRequest : pprList) {
            productIds.add(promotionProductRequest.getMpId());
        }

        Integer ret = pmpService.saveBatch(ppr.getProductPromotionList());

        PromotionLimitRuleEntity limitEntity =new PromotionLimitRuleEntity();

        // 添加促销商品的限制项，
        for(PromotionProductRequest promotionProduct : ppr.getProductPromotionList()){
            PromotionLimitRuleEntity dbEntity = limitService.getEntityByPromotionIdAndMpId(
                    promotionProduct.getPromotionId(), promotionProduct.getMpId());
            if(dbEntity!=null){
                continue;
            }
            limitEntity.setPromotionId(promotionProduct.getPromotionId());
            limitEntity.setProductId(promotionProduct.getMpId());
            limitService.addPromotionLimitRule(limitEntity);
        }
        return RestResult.success(ret);
    }

    @PostMapping("/saveBatchV2")
    @Override
    public RestResult<Integer> saveBatchV2(@RequestBody PromotionProductSaveListRequest ppr) {
        log.info("-----进入批量保存促销活动商品--ppr:{}-----",ppr);
        // 查询当前商品哪些已经添加过了，则跳过
        Long promotionId =null;
        List<Long> productIds =new ArrayList<>();
        List<PromotionProductRequest> pprList =ppr.getProductPromotionList();
        for (PromotionProductRequest temp : pprList) {
            promotionId =temp.getPromotionId();
            PromotionMerchantProductEntity dbEntity =
                    pmpService.queryEntityByPromotionIdAndMpId(temp.getPromotionId(), temp.getMpId());
            if(dbEntity !=null){
                continue;
            }
            productIds.add(temp.getMpId());
        }

        if(productIds ==null || productIds.isEmpty()){
            log.info("----在批量保存促销活动商品中，productIds为空----");
            return RestResult.success(1);
        }

        // 远程调用商品服务，查询子商品
//        log.info("-----进入批量保存促销活动商品--远程调用商品服务，查询子商品--productIds:{}-----",productIds);
//        RestResult<List<ProductAfterResponse>> listRestResult =
//                productListApi.queryProductList(productIds);
//        log.info("-----进入批量保存促销活动商品--远程调用商品服务完毕，查询子商品--productIds:{}-----",productIds);
//        List<ProductAfterResponse> productAfterList = listRestResult.getData();
//        // 组装productList
//        List<PromotionMerchantProductEntity> productListNew =new ArrayList<>();
//        for (ProductAfterResponse productAfterResponse : productAfterList) {
//            List<ProductAfterSonResponse> productAfterSonResponse =
//                    productAfterResponse.getProductAfterSonResponse();
//            // 如果是不是普通商品，则存储需要存在外部信息
//            if(!TypeOfProductEnum.NORMAL.getCode().equals(productAfterResponse.getTypeOfProduct())){
//                log.info("--------系列主品--------");
//                PromotionMerchantProductEntity productEntity =
//                        assembleMainSeriesPromotionProduct(promotionId, productAfterResponse);
//                productListNew.add(productEntity);
//            }
//            // 组装productList son  包括系列子品，普通商品
//            for (ProductAfterSonResponse afterSonResponse : productAfterSonResponse) {
//                PromotionMerchantProductEntity productEntityForSon =
//                        assemblePromotionSonProduct(promotionId, afterSonResponse);
//                productListNew.add(productEntityForSon);
//            }
//        }

        // 用于添加到 promotion_merchant_product里
//        List<PromotionMerchantProductEntity> productListDB = pmpService.saveBatchV2(productListNew);

        // 判断是否和其他活动冲突
//        for (PromotionMerchantProductEntity stayProduct : productListDB) {
//            JudgeCurrProductRequest jcpReq =new JudgeCurrProductRequest();
//            jcpReq.setCurrPromotionId(stayProduct.getPromotionId());
//            jcpReq.setMpId(stayProduct.getMpId());
//            jcpReq.setPromotionMerchantProductId(stayProduct.getId());
//            JudgeCurrProductResponse judgeCurrProductResponse = pmpService.queryPromotionForCurrProduct(jcpReq);
//            // 如果有与其他活动互斥
//            if(judgeCurrProductResponse.getPromotionProductMutexFlag()){
//                //更新 stayProduct 互斥标识  互斥
//                PromotionMerchantProductEntity stayProductSetDb =new PromotionMerchantProductEntity();
//                stayProductSetDb.setId(stayProduct.getId());
//                //互斥
//                stayProductSetDb.setMutexFlag(MutexFlagEnum.MUTEX.getCode());
//                pmpService.updateEntity(stayProductSetDb);
//            }
//        }

        // 添加促销商品的限制项，
        // 用于添加到 promotion_limit_rule里，需要指定limit_type为GOODS:商品
        log.info("----进入批量保存促销活动商品--添加促销商品的限制项--当前促销id:{}--",promotionId);
//        for (PromotionMerchantProductEntity promotionProduct : productListDB){
//            PromotionLimitRuleEntity dbEntity = limitService.getEntityByPromotionIdAndMpId(
//                    promotionProduct.getPromotionId(), promotionProduct.getMpId());
//            if(dbEntity != null){
//                continue;
//            }
//            PromotionLimitRuleEntity limitEntity =new PromotionLimitRuleEntity();
//            limitEntity.setPromotionId(promotionProduct.getPromotionId());
//            limitEntity.setLimitType(LimitTypeEnum.GOODS.getCode());
//            // 之前是在修改 limitEntity中productId，现修改为 limitRef
//            limitEntity.setLimitRef(promotionProduct.getMpId());
//
//            limitService.addPromotionLimitRule(limitEntity);
//        }
        return RestResult.success(1);
    }

//    private PromotionMerchantProductEntity assemblePromotionSonProduct(Long promotionId, ProductAfterSonResponse afterSonResponse) {
//        PromotionMerchantProductEntity productEntityForSon =new PromotionMerchantProductEntity();
//        productEntityForSon.setMpId(afterSonResponse.getId());
//        productEntityForSon.setPromotionId(promotionId);
//        productEntityForSon.setMpCode(afterSonResponse.getCode());
//        productEntityForSon.setMpName(afterSonResponse.getChineseName());
//        if (afterSonResponse.getParentId() ==0){
//            productEntityForSon.setTypeOfProduct(TypeOfProductEnum.NORMAL.getCode());
//        }else{
//            productEntityForSon.setTypeOfProduct(TypeOfProductEnum.SUB_SERIES.getCode());
//        }
//        productEntityForSon.setMpParentId(afterSonResponse.getParentId());
//        productEntityForSon.setBarcode(afterSonResponse.getBarCode());
////            productEntityForSon.setBarcodeId(afterSonResponse);
//        productEntityForSon.setCategoryId(afterSonResponse.getCategoryId());
//        productEntityForSon.setCategoryName(afterSonResponse.getFullNamePath());
//        productEntityForSon.setMerchantId(afterSonResponse.getMerchantId());
//        productEntityForSon.setMerchantName(afterSonResponse.getMerchantName());
//        productEntityForSon.setPicUrl(afterSonResponse.getPictureUrl());
//        productEntityForSon.setScopeType(ProductScopeTypeEnum.PRODUCT.getCode());
//        productEntityForSon.setSalePriceWithTax(afterSonResponse.getSalePriceWithTax());
//        productEntityForSon.setStoreId(afterSonResponse.getStoreId());
//        productEntityForSon.setStoreName(afterSonResponse.getStoreName());
//        return productEntityForSon;
//    }

//    private PromotionMerchantProductEntity assembleMainSeriesPromotionProduct(Long promotionId, ProductAfterResponse productAfterResponse) {
//        PromotionMerchantProductEntity productEntity =new PromotionMerchantProductEntity();
//        productEntity.setMpId(productAfterResponse.getId());
//        productEntity.setPromotionId(promotionId);
//        productEntity.setMpCode(productAfterResponse.getCode());
//        productEntity.setMpName(productAfterResponse.getChineseName());
//        productEntity.setMpParentId(0L);
//        //系列主品
//        productEntity.setTypeOfProduct(TypeOfProductEnum.MAIN_SERIES.getCode());
//        productEntity.setBarcode(productAfterResponse.getBarCode());
////            productEntity.setBarcodeId(productAfterResponse);
//        productEntity.setCategoryId(productAfterResponse.getCategoryId());
//        productEntity.setCategoryName(productAfterResponse.getFullNamePath());
//        productEntity.setMerchantId(productAfterResponse.getMerchantId());
//        productEntity.setMerchantName(productAfterResponse.getMerchantName());
//        productEntity.setPicUrl(productAfterResponse.getPictureUrl());
//        productEntity.setScopeType(ProductScopeTypeEnum.PRODUCT.getCode());
//        productEntity.setSalePriceWithTax(productAfterResponse.getSalePriceWithTax());
//        productEntity.setStoreId(productAfterResponse.getStoreId());
//        productEntity.setStoreName(productAfterResponse.getStoreName());
//        return productEntity;
//    }

    @RequestMapping("/getProductList")
    @Override
    public RestResult<PageResult<PromotionProductResponse>> getPromotionProductList(
            @RequestBody PromotionProductQueryListRequest ppqlRequest) {
        PromotionMerchantProductEntity condition =new PromotionMerchantProductEntity();
        BeanUtils.copyProperties(ppqlRequest,condition);
        Pagination pagination =new Pagination();
        pagination.setLimitStart((ppqlRequest.getStart()-1) * ppqlRequest.getLimit());
        pagination.setPageSize(ppqlRequest.getLimit());
        condition.setDeleteFlag(DeleteFlagEnum.UN_DELETE.getCode());
        condition.setCreatorName(null);
        condition.setCreator(null);
        condition.setUpdator(null);
        condition.setUpdatorName(null);
        // 只查一层
        condition.setMpParentId(0L);
        List<PromotionMerchantProductEntity> productList = pmpService.
                findOfPage(condition, pagination);
        Integer count = pmpService.countOfPage(condition);
        List<PromotionProductResponse> responseList = null;
        if(productList !=null && !productList.isEmpty()){
            responseList = ListUtils.entityListToModelList(
                    productList, PromotionProductResponse.class);
        }


        if(responseList !=null && !responseList.isEmpty()){
            for (PromotionProductResponse pp : responseList) {
                PromotionMerchantProductEntity conditionSon =new PromotionMerchantProductEntity();
                BeanUtils.copyProperties(ppqlRequest,conditionSon);
                Pagination paginationSon =new Pagination();
                paginationSon.setLimitStart(0);
                paginationSon.setPageSize(10);
                conditionSon.setPromotionId(ppqlRequest.getPromotionId());
                conditionSon.setDeleteFlag(DeleteFlagEnum.UN_DELETE.getCode());
                // 父商品id
                conditionSon.setMpParentId(pp.getMpId());
                List<PromotionMerchantProductEntity> productListSon = pmpService.
                        findOfPage(conditionSon, paginationSon);

                List<PromotionProductSonResponse> responseListSon = null;
                if (productListSon !=null && !productListSon.isEmpty()){
                    responseListSon = ListUtils.entityListToModelList(
                            productListSon, PromotionProductSonResponse.class);
                }

                if(responseListSon !=null && !responseListSon.isEmpty()){
                    for (PromotionProductSonResponse ppSon : responseListSon) {
                        PromotionLimitRuleEntity promotionLimitRuleSon = limitService.getEntityByPromotionIdAndMpId(ppSon.getPromotionId(), ppSon.getMpId());
                        if(promotionLimitRuleSon !=null){
                            ppSon.setPlatformTotalLimit(promotionLimitRuleSon.getPlatformTotalLimit());
                            ppSon.setChannelMerchantLimit(promotionLimitRuleSon.getChannelMerchantLimit());
                            ppSon.setChannelStoreLimit(promotionLimitRuleSon.getChannelStoreLimit());
                            ppSon.setChannelIndividualLimit(promotionLimitRuleSon.getChannelIndividualLimit());
                            ppSon.setTotalLimit(promotionLimitRuleSon.getTotalLimit());
                            ppSon.setIndividualLimit(promotionLimitRuleSon.getIndividualLimit());
                            ppSon.setTotalLimitAmount(promotionLimitRuleSon.getTotalLimitAmount());
                            ppSon.setOrderLimit(promotionLimitRuleSon.getOrderLimit());
                            ppSon.setLimitRuleId(promotionLimitRuleSon.getId());
                        }
                    }
                }

                pp.setChildren(responseListSon);
                PromotionLimitRuleEntity promotionLimitRule = limitService.getEntityByPromotionIdAndMpId(pp.getPromotionId(), pp.getMpId());
                if (promotionLimitRule !=null){
                    pp.setPlatformTotalLimit(promotionLimitRule.getPlatformTotalLimit());
                    pp.setChannelMerchantLimit(promotionLimitRule.getChannelMerchantLimit());
                    pp.setChannelStoreLimit(promotionLimitRule.getChannelStoreLimit());
                    pp.setChannelIndividualLimit(promotionLimitRule.getChannelIndividualLimit());
                    pp.setTotalLimit(promotionLimitRule.getTotalLimit());
                    pp.setIndividualLimit(promotionLimitRule.getIndividualLimit());
                    pp.setTotalLimitAmount(promotionLimitRule.getTotalLimitAmount());
                    pp.setOrderLimit(promotionLimitRule.getOrderLimit());
                    pp.setLimitRuleId(promotionLimitRule.getId());
                }

//                if (MutexFlagEnum.MUTEX.getCode().equals(ppqlRequest.getMutexFlag())){
//                    // 根据促销 id，和商品 id 查看该商品互斥活动
//                    PromotionMutexEntity conditionMutex =new PromotionMutexEntity();
//                    conditionMutex.setPromotionId(pp.getPromotionId());
//                    conditionMutex.setPromotionMerchantProductId(pp.getId());
//                    conditionMutex.setDeleteFlag(DeleteFlagEnum.UN_DELETE.getCode());
//                    PromotionMutexEntity promotionMutexEntity =
//                            promotionMutexService.getPromotionMutexEntity(conditionMutex);
//                    if(promotionMutexEntity !=null){
//                        //设置互斥记录时间
//                        pp.setMutexTime(promotionMutexEntity.getCreateTime());
//                    }
//                }
            }
        }

        PageResult<PromotionProductResponse> pageResult =new PageResult<>();
        pageResult.setRows(responseList);
        pageResult.setTotal(count);
        return RestResult.success(pageResult);
    }

    @PostMapping("deleteProductBatch")
    @Override
    public RestResult deleteProductBatch(@RequestBody DeleteProductBatchRequest request) {
        if(CollectionUtils.isNotEmpty(request.getMpIds())){
            pmpService.deleteProductBatch(request.getMpIds());
        }
        return RestResult.success(null);
    }

    /*
    * 单一促销活动保存
    * */
    @PostMapping("/saveBatchPromotionalProduct")
    public RestResult<Integer> saveBatchPromotionalProduct(@RequestBody PromotionProductSaveListRequest ppr) {
        log.info("-----进入批量保存促销活动商品--ppr:{}-----",ppr);
        // 查询当前商品哪些已经添加过了，则跳过
        Long promotionId =null;
        List<Long> productIds =new ArrayList<>();
        List<PromotionProductRequest> pprList =ppr.getProductPromotionList();
        for (PromotionProductRequest temp : pprList) {
            promotionId =temp.getPromotionId();
            PromotionMerchantProductEntity dbEntity =
                    pmpService.queryEntityByPromotionIdAndMpId(temp.getPromotionId(), temp.getMpId());
            if(dbEntity !=null){
                continue;
            }
            productIds.add(temp.getMpId());
        }

        if(productIds ==null || productIds.isEmpty()){
            log.info("----在批量保存促销活动商品中，productIds为空----");
            return RestResult.success(1);
        }

        // 远程调用商品服务，查询子商品
//        log.info("-----进入批量保存促销活动商品--远程调用商品服务，查询子商品--productIds:{}-----",productIds);
//        RestResult<List<ProductAfterResponse>> listRestResult =
//                productListApi.queryProductList(productIds);
//        log.info("-----进入批量保存促销活动商品--远程调用商品服务完毕，查询子商品--productIds:{}-----",productIds);
//        List<ProductAfterResponse> productAfterList = listRestResult.getData();
//        // 组装productList
//        List<PromotionMerchantProductEntity> productListNew =new ArrayList<>();
//        for (ProductAfterResponse productAfterResponse : productAfterList) {
//            List<ProductAfterSonResponse> productAfterSonResponse =
//                    productAfterResponse.getProductAfterSonResponse();
//            // 如果是不是普通商品，则存储需要存在外部信息
//            if(!TypeOfProductEnum.NORMAL.getCode().equals(productAfterResponse.getTypeOfProduct())){
//                log.info("--------系列主品--------");
//                PromotionMerchantProductEntity productEntity =
//                        assembleMainSeriesPromotionProduct(promotionId, productAfterResponse);
//                productListNew.add(productEntity);
//            }
//            // 组装productList son  包括系列子品，普通商品
//            for (ProductAfterSonResponse afterSonResponse : productAfterSonResponse) {
//                PromotionMerchantProductEntity productEntityForSon =
//                        assemblePromotionSonProduct(promotionId, afterSonResponse);
//                productListNew.add(productEntityForSon);
//            }
//        }

        // 用于添加到 promotion_merchant_product里
//        List<PromotionMerchantProductEntity> productListDB = pmpService.saveBatchV2(productListNew);
//
//        // 添加促销商品的限制项，
//        // 用于添加到 promotion_limit_rule里，需要指定limit_type为GOODS:商品
//        log.info("----进入批量保存促销活动商品--添加促销商品的限制项--当前促销id:{}--",promotionId);
//        for (PromotionMerchantProductEntity promotionProduct : productListDB){
//            PromotionLimitRuleEntity dbEntity = limitService.getEntityByPromotionIdAndMpId(
//                    promotionProduct.getPromotionId(), promotionProduct.getMpId());
//            if(dbEntity != null){
//                continue;
//            }
//            PromotionLimitRuleEntity limitEntity =new PromotionLimitRuleEntity();
//            limitEntity.setPromotionId(promotionProduct.getPromotionId());
//            limitEntity.setLimitType(LimitTypeEnum.GOODS.getCode());
//            // 之前是在修改 limitEntity中productId，现修改为 limitRef
//            limitEntity.setLimitRef(promotionProduct.getMpId());
//            limitEntity.setProductId(promotionProduct.getMpId());
//
//            limitService.addPromotionLimitRule(limitEntity);
//        }

        // 添加单一促销商品的限制项，
        // 用于添加到 promotion_single_rule
        log.info("----进入批量保存促销活动商品--添加促销商品的限制项--当前促销id:{}--",promotionId);
//        for (PromotionMerchantProductEntity promotionProduct : productListDB){
////            PromotionLimitRuleEntity dbEntity = limitService.getEntityByPromotionIdAndMpId(
////                    promotionProduct.getPromotionId(), promotionProduct.getMpId());
//            PromotionSingleRuleEntity limitEntity =new PromotionSingleRuleEntity();
//            limitEntity.setPromotionId(promotionProduct.getPromotionId());
//            limitEntity.setProductId(promotionProduct.getMpId());
//            promotionSingleLimitRuleService.addPromotionSingleLimitRule(limitEntity);
//        }
        return RestResult.success(1);
    }
}
